package edu.kaist.cs442.server.locationalpush.common.mobile;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.DatastoreImpl;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: duyleekun
 * Date: 2/29/12
 * Time: 3:59 PM
 * To change this template use File | Settings | File Templates.
 */
@Configuration
public class MobileDAOImpl implements MobileDAO {

    @Autowired(required = true)
    private Datastore datastore;

	@Autowired(required = true)
	private Morphia morphia;

	@PostConstruct
	private void init()
	{
		morphia.map(MobileVO.class);
		datastore.ensureIndexes();
	}

    @Override
    public int update(MobileVO mobile) {
        UpdateOperations<MobileVO> updateOperations = datastore.createUpdateOperations(MobileVO.class);
	    if (mobile.getRegistrationId() != null)
            updateOperations.set("registrationId", mobile.getRegistrationId());
	    if ((mobile.getLocation() != null))
            updateOperations.set("location", mobile.getLocation());


        Query<MobileVO> updateQuery = datastore.createQuery(MobileVO.class).field("uuid").equal(mobile.getUuid());

        return datastore.update(updateQuery, updateOperations, true).getUpdatedCount();
    }

    @Override
    public String getRegistrationId(String uuid) {
	    MobileVO currentMobile = datastore.find(MobileVO.class,"uuid",uuid).get();
        return currentMobile.getRegistrationId();
    }

	@Override
	public List<MobileVO> getNearby(double latitude, double longitude, double diameter) {
		return datastore.find(MobileVO.class).field("location").within(latitude,longitude,diameter).asList();
	}
}
